package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        //Shop shop = queryWithPassThrough(id);

        // 互斥锁解决缓存击穿
//        Shop shop = queryWithPassMutex(id);

        // 逻辑过期解决缓存击穿
       //Shop shop = queryWithLogicalExpire(id);

//        Shop shop = cacheClient.queryWithPassThrough(id, Shop.class, CACHE_SHOP_KEY, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES); // 缓存穿透
        // 缓存击穿
        Shop shop = cacheClient.queryWithLogicalExpire(
                CACHE_SHOP_KEY, id, Shop.class,
                this::getById,
                CACHE_SHOP_TTL, TimeUnit.MINUTES
        );
        if (shop == null){
            return Result.fail("店铺不存在");
        }

        return Result.ok(shop);
    }

//    public Shop queryWithPassMutex(Long id){
//        // 先从redis查询
//        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//        // 判断是否存在
//        if (StrUtil.isNotBlank(shopJson)) {
//            // 存在，直接返回
//            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//            return shop;
//        }
//        //如果命中的是空值
//        if (shopJson != null) {
//            return null;
//        }
//
//        //获取互斥锁
//        String lockKey = LOCK_SHOP_KEY + id;
//        boolean isLock = tryLock(lockKey);
//        Shop shop = null;
//        try {
//            if (!isLock) {
//                // 获取锁失败，休眠并重试
//                    Thread.sleep(50);
//                return queryWithPassMutex(id);
//            }
//
//            //不存在，去查数据库
//            shop = getById(id);
//            //模拟重建的延时操作
//            Thread.sleep(200);
//            // 判断数据库是否存在,不存在，返回错误
//            if (shop == null) {
//
//                //将空值写入redis中
//                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
//
//                return null;
//            }
//            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }finally {
//            unLock(lockKey);
//        }
//
//
//        return shop;
//    }


    public Shop queryWithPassThrough(Long id){
        // 先从redis查询
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        // 判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //如果命中的时空值
        if (shopJson != null) {
            return null;
        }

        //不存在，去查数据库
        Shop shop = getById(id);
        // 判断数据库是否存在,不存在，返回错误
        if (shop == null) {

            //将空值写入redis中
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",CACHE_NULL_TTL, TimeUnit.MINUTES);

            return null;
        }
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

//    public Shop queryWithLogicalExpire(Long id){
//        // 先从redis查询
//        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//        // 判断是否存在
//        if (StrUtil.isBlank(shopJson)) {
//
//            return null;
//        }
//
//        //存在，需要将 json反序列化 转换为对象
//        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
//        JSONObject data = (JSONObject) redisData.getData();
//        Shop shop = JSONUtil.toBean(data, Shop.class);
//        LocalDateTime expireTime = redisData.getExpireTime();
//        //判断是否过期
//        if (expireTime.isAfter(LocalDateTime.now())) {
//            //未过期，直接返回数据
//            return shop;
//        }
//
//        //过期，尝试获取互斥锁，获取失败直接返回旧结果，获取成功，开启独立线程，实现缓存重建
//        String lockKey = LOCK_SHOP_KEY + id;
//        boolean isLock = tryLock(lockKey);
//        if (isLock) {
//            CACHE_REBUILD_EXECUTOR.submit(() -> {
//                try {
//                    // 重建缓存
//                    this.saveShop2Redis(id, 20L);
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }finally {
//                    unLock(lockKey);
//                }
//
//            });
//
//        }
//
//
//
//        return shop;
//    }



//    private boolean tryLock(String key) {
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
//        return BooleanUtil.isTrue(flag);
//    }

//    private void unLock(String key) {
//        stringRedisTemplate.delete(key);
//    }

//    public void saveShop2Redis(Long id, Long expireSeconds) {
//        //查询店铺数据
//        Shop shop = getById(id);
//        // 将随机时间和数据封装到RedisData实体类当中去
//        RedisData redisData = new RedisData();
//        redisData.setData(shop);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//
//        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
//
//    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        //先对shop_id进行判断是否存在
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺不存在");
        }

        // 先更新数据库
        updateById(shop);

        //删除redis缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        return Result.ok();

    }


}
